package com.paradogs.gs.modules.friend;

import com.paradogs.framework.database.ParadogsDBAsyncThread;
import com.paradogs.gs.misc.DBMultiRowManager;
import com.paradogs.gs.misc.annotations.GameManager;
import com.paradogs.gs.modules.Player;
import com.paradogs.gs.db.Friend;
import com.paradogs.gs.db.FriendApply;
import com.paradogs.gs.modules.friend.dao.FriendApplyDao;
import com.paradogs.gs.modules.friend.dao.FriendDao;
import com.paradogs.gs.utils.PlayerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @author: yumi
 * @date: 2024/12/23  14:39
 * @Description: 好友申请
 */
@Slf4j
@GameManager
public class FriendApplyMgr extends DBMultiRowManager<FriendApplyDao, FriendApply> {

    @Autowired
    private FriendDao friendDao;

    @Override
    public void onInitialization(Map<Long, FriendApply> data) {

    }

    /** 尝试插入一个好友申请 */
    public boolean tryAddOneApply(Long applyUid, String applyName) {
        FriendApply apply = newInstance();
        apply.setApplyUid(applyUid);
        apply.setApplyName(applyName);
        __update__(apply);
        return true;
    }

    public void agree(Long applyId) {
        FriendApply apply = get(applyId);
        if (apply == null) return;
        // 删除申请
        owner().friendApplyMgr().__del__(apply);
        // 己方新增好友
        if (!owner().friendMgr().has(apply.getId())) {
            Friend friend = owner().friendMgr().newInstance();
            friend.setFriendId(apply.getApplyUid());
            friend.setFriendName(apply.getApplyName());
            owner().friendMgr().__update__(friend);
        }
        // 对方新增好友
        Player target = PlayerUtils.getPlayer(apply.getApplyUid());
        if (target != null) {
            if (!target.friendMgr().has(owner().getId())) {
                Friend friend = target.friendMgr().newInstance();
                friend.setFriendId(apply.getApplyUid());
                friend.setFriendName(apply.getApplyName());
                target.friendMgr().__update__(friend);
            }
        } else {
            // 对方不在线
            ParadogsDBAsyncThread.join(apply.getApplyUid(), () -> {
                Friend friend = new Friend(owner().getId(), owner().roleMgr().__raw__().getNickName());
                friend.setUid(apply.getApplyUid());
                friendDao.saveOrUpdate(friend);
            });
        }

    }
}
